package com.headwind.async;

import java.util.concurrent.*;

/**
 * @author : Headwind
 * @version : 1.0
 * @date : Created in 2020/8/8
 * @description : 使用FutureTask实现异步化
 */
public class FutureTaskSamples {

    /**
     * 获取处理器数量
     */
    private final static int CPUS = Runtime.getRuntime().availableProcessors();
    /**
     * 初始化线程池
     */
    private final static ThreadPoolExecutor THREAD_POOL_EXECUTOR =
            new ThreadPoolExecutor(CPUS, CPUS * 2, 1, TimeUnit.MINUTES,
                    new LinkedBlockingQueue<>(5), new ThreadPoolExecutor.CallerRunsPolicy());

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
        // 创建future任务
        FutureTask<String> futureTask = new FutureTask<String>(() -> {
            String result = task1();
            return result;
        });
        // 显示使用Thread开启异步执行任务1
        Thread thread = new Thread(futureTask, "Thread1");
        thread.start();
        // 使用线程池来开启异步实行任务1
//        THREAD_POOL_EXECUTOR.execute(futureTask);
        // 执行任务2
        String task2Result = task2();
        // 同步等待任务1运行结束
        String task1Result = futureTask.get();
        // 输出两个任务的执行结果
        System.out.println(task1Result + "=====" + task2Result);
        System.out.println(System.currentTimeMillis() - start);
//        THREAD_POOL_EXECUTOR.shutdown();
    }

    /**
     * 任务1
     *
     * @return 字符串
     */
    public static String task1() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("----Do task1----");
        return "task1";
    }

    /**
     * 任务2
     *
     * @return 字符串
     */
    public static String task2() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("----Do task2----");
        return "task2";
    }

}
